package bookmanagementsystem.gui;

import bookmanagementsystem.dao.AdminDAO;
import bookmanagementsystem.dao.BookDAO;
import bookmanagementsystem.dao.BorrowingDAO;
import bookmanagementsystem.dao.ReturningDAO;
import bookmanagementsystem.model.Admin;
import bookmanagementsystem.model.Book;
import bookmanagementsystem.model.BorrowingRecord;
import bookmanagementsystem.model.ReturningRecord;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;

import java.util.Date;
import java.util.List;

public class AdminMainFrame extends JFrame {
    private JLabel welcomeLabel;
    // 新增组件用于图书管理功能
    private JTextField bookIDField;
    private JTextField bookNameField;
    private JTextField authorNameField;
    private JTextField quantityInLibraryField;
    private JTextField locationField;
    private JButton addBookButton;
    private JButton queryBookButton;
    private JButton deleteBookButton;
    private JButton modifyPasswordButton;
    private JButton modifyBookInfoButton;
    // 新增查询借书
    private JButton queryBorrowingRecordsButton;
    // 新增查询还书
    private JButton queryReturningRecordsButton;
    private JList<String> bookList;
    private DefaultListModel<String> listModel;
    // 用于存储当前登录管理员的ID
    private String currentAdminID;

    public AdminMainFrame(String adminID) {
        this.currentAdminID = adminID;
        setTitle("图书管理系统 - 管理员主界面");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initComponents();
        addComponentsToFrame();
        addActionListeners();
    }

    private void initComponents() {
        // 初始化欢迎标签
        welcomeLabel = new JLabel("欢迎来到图书管理系统管理员主界面！");

        // 初始化图书管理相关组件
        bookIDField = new JTextField(20);
        bookNameField = new JTextField(20);
        authorNameField = new JTextField(20);
        quantityInLibraryField = new JTextField(20);
        locationField = new JTextField(20);
        addBookButton = new JButton("添加图书");
        queryBookButton = new JButton("查询图书");
        deleteBookButton = new JButton("删除图书");
        modifyPasswordButton = new JButton("修改密码");
        modifyBookInfoButton = new JButton("修改图书信息");
        // 初始化查询借书记录按钮
        queryBorrowingRecordsButton = new JButton("查询借书记录");
        // 初始化查询还书记录按钮
        queryReturningRecordsButton = new JButton("查询还书记录");

        // 初始化图书列表组件
        listModel = new DefaultListModel<>();
        bookList = new JList<>(listModel);
    }

    private void addComponentsToFrame() {
        // 主面板，采用BorderLayout布局，划分不同功能区域
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 上部面板，放置欢迎标签，采用FlowLayout
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        topPanel.add(welcomeLabel);

        // 中部面板，用于放置图书管理相关操作组件，，每个子面板采用FlowLayout排列组件
        JPanel middlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        // 子面板1：图书信息输入相关组件，使用GridLayout
        JPanel bookInfoPanel = new JPanel(new GridLayout(0, 1));

        JPanel bookIDRowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        bookIDRowPanel.add(new JLabel("图书ID ："));
        bookIDRowPanel.add(bookIDField);
        bookInfoPanel.add(bookIDRowPanel);

        JPanel bookNameRowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        bookNameRowPanel.add(new JLabel("图书名称："));
        bookNameRowPanel.add(bookNameField);
        bookInfoPanel.add(bookNameRowPanel);

        JPanel authorRowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        authorRowPanel.add(new JLabel("图书作者："));
        authorRowPanel.add(authorNameField);
        bookInfoPanel.add(authorRowPanel);

        JPanel quantityRowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        quantityRowPanel.add(new JLabel("库存数量："));
        quantityRowPanel.add(quantityInLibraryField);
        bookInfoPanel.add(quantityRowPanel);

        JPanel locationRowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        locationRowPanel.add(new JLabel("存放位置："));
        locationRowPanel.add(locationField);
        bookInfoPanel.add(locationRowPanel);

        middlePanel.add(bookInfoPanel);

        // 子面板2：操作按钮相关组件（添加、查询、删除图书等）
        JPanel operationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        operationPanel.add(addBookButton);
        operationPanel.add(queryBookButton);
        operationPanel.add(deleteBookButton);
        operationPanel.add(modifyPasswordButton);
        operationPanel.add(modifyBookInfoButton);

        // 子面板3：借书、还书记录查询相关组件
        JPanel recordQueryPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        recordQueryPanel.add(queryBorrowingRecordsButton);
        recordQueryPanel.add(queryReturningRecordsButton);

        middlePanel.add(operationPanel);
        middlePanel.add(recordQueryPanel);

        // 下部面板，放置图书列表展示相关组件，采用BorderLayout布局
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(new JLabel("图书列表："), BorderLayout.NORTH);
        bottomPanel.add(new JScrollPane(bookList), BorderLayout.CENTER);

        // 将各部分面板添加到主面板相应区域
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(middlePanel, BorderLayout.CENTER);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        getContentPane().add(mainPanel);
    }

    private void addActionListeners() {
        addBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                String bookName = bookNameField.getText();
                String authorName = authorNameField.getText();
                // 自动生成入库时间
                Timestamp entryTime = new Timestamp(System.currentTimeMillis());
                int quantityInLibrary;
                try {
                    quantityInLibrary = Integer.parseInt(quantityInLibraryField.getText());
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "请重新输入。");
                    return;
                }
                String location = locationField.getText();
                Book book = new Book(bookID, bookName, authorName, entryTime, quantityInLibrary, location);
                BookDAO bookDAO = new BookDAO();
                if (bookDAO.addBook(book)) {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "图书添加成功！");
                    updateBookList();
                } else {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "图书添加失败，请检查输入信息或联系管理员。");
                }
            }
        });

        queryBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText().trim();
                String bookName = bookNameField.getText().trim();
                BookDAO bookDAO = new BookDAO();
                Book book = null;
                if (!bookID.isEmpty()) {
                    book = bookDAO.queryBookById(bookID);
                } else if (!bookName.isEmpty()) {
                    book = bookDAO.queryBookByName(bookName);
                }
                showQueryResult(book);
            }
        });

        deleteBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                BookDAO bookDAO = new BookDAO();
                if (bookDAO.deleteBook(bookID)) {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "图书删除成功！");
                    updateBookList();
                } else {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "图书删除失败，请检查输入信息或联系管理员。");
                }
            }
        });

        modifyPasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 打开修改密码界面
                ModifyPasswordFrame modifyPasswordFrame = new ModifyPasswordFrame(currentAdminID);
                modifyPasswordFrame.setVisible(true);
            }
        });

        modifyBookInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 打开修改图书信息界面
                ModifyBookInfoFrame modifyBookInfoFrame = new ModifyBookInfoFrame();
                modifyBookInfoFrame.setVisible(true);
            }
        });

        // 查询借书记录按钮的点击事件处理逻辑，根据用户ID查询
        queryBorrowingRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userID = JOptionPane.showInputDialog(AdminMainFrame.this, "请输入要查询借书记录的用户ID：");
                if (userID!= null &&!userID.isEmpty()) {
                    BorrowingDAO borrowingDAO = new BorrowingDAO();
                    List<BorrowingRecord> borrowingRecords = borrowingDAO.queryBorrowingRecordsByUser(userID);
                    BorrowingRecordsFrame borrowingRecordsFrame = new BorrowingRecordsFrame(borrowingRecords);
                    borrowingRecordsFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "用户ID不能为空，请重新输入。");
                }
            }
        });

        // 查询还书记录按钮的点击事件处理逻辑，根据用户ID查询
        queryReturningRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userID = JOptionPane.showInputDialog(AdminMainFrame.this, "请输入要查询还书记录的用户ID：");
                if (userID!= null &&!userID.isEmpty()) {
                    ReturningDAO returningDAO = new ReturningDAO();
                    List<ReturningRecord> returningRecords = returningDAO.queryReturningRecordsByUser(userID);
                    ReturningRecordsFrame returningRecordsFrame = new ReturningRecordsFrame(returningRecords);
                    returningRecordsFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(AdminMainFrame.this, "用户ID不能为空，请重新输入。");
                }
            }
        });

        updateBookList();
    }

    private void updateBookList() {
        listModel.clear();
        BookDAO bookDAO = new BookDAO();
        for (Book book : bookDAO.queryAllBooks()) {
            listModel.addElement(book.getBookID() + " - " + book.getBookName());
        }
    }

    private void showQueryResult(Object result) {
        if (result instanceof Book) {
            Book book = (Book) result;
            if (book!= null) {
                JOptionPane.showMessageDialog(AdminMainFrame.this, "查询到图书信息如下：\n图书ID：" + book.getBookID() + "\n图书名称：" + book.getBookName() + "\n作者：" + book.getAuthorName() + "\n入库时间：" + book.getEntryTime() + "\n库存数量：" + book.getQuantityInLibrary() + "\n存放位置：" + book.getLocation());
            }
        }
    }
}